<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="getList(1)">
        <a-row :gutter="16">
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('项目信息')" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
              <a-input :placeholder="$t('请输入项目编码/名称')" v-model="queryParam.gameInfo" />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('管理状态')" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
              <a-select v-model="queryParam.state">
                <a-select-option value="">{{$t('全部')}}</a-select-option>
                <a-select-option value="Y">{{$t('是')}}</a-select-option>
                <a-select-option value="N">{{$t('否')}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="8" :md="12" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="getList(1)" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('重置') }}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button v-has="'BisGameController:add'" type="primary" @click="handleAdd" icon="plus">{{$t('新增项目')}}</a-button>
    </div>
    <a-row style="border: 1px solid #d9d9d9">
      <a-col :span="3">
        <a-tree
          ref="treeBox"
          :tree-data="sortList"
          :props="defaultProps"
          style="background-color: #fff"
          :defaultSelectedKeys="defaultSelectedKeys"
          @select="treeSelect"
        />
      </a-col>
      <a-col :span="21" style="border-left: 1px solid #d9d9d9">
        <a-row>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            class="j-table-force-nowrap"
            :pagination="ipagination"
            @change="handleTableChange"
          >
            <span slot="action" slot-scope="text, record">
              <a v-has="'BisGameController:edit'" @click="handleEdit(record)">{{$t('编辑')}}</a>&nbsp;&nbsp;
              <a-popconfirm v-has="'BisGameController:delete'" :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
                <a>{{$t('删除')}}</a>
              </a-popconfirm>
            </span>
            <span slot="states" slot-scope="text, record">
              <a-switch v-enable-if="'BisGameController:edit'" v-model="record.states" @change="onChange(record)"></a-switch>
            </span>
          </a-table>
        </a-row>
      </a-col>
    </a-row>
    <game-modal ref="modalForm" @ok="modalFormOk"></game-modal>
  </a-card>
</template>
<script>
import { getAction, deleteAction, postAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import GameModal from './modules/GameModal'

export default {
  name: 'ProjectManage',
  components: {
    GameModal,
  },
  data() {
    return {
      description: '娱乐项目管理页面',
      loading: false,
      columns: [
        {
          title: this.$t('项目编码'),
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: this.$t('项目名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('项目分类'),
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: this.$t('管理状态'),
          align: 'center',
          dataIndex: 'states',
          scopedSlots: { customRender: 'states' },
        },
        {
          title: this.$t('消费方式'),
          align: 'center',
          dataIndex: 'consumeType_dictText',
        },
        {
          title: this.$t('绑定商品'),
          align: 'center',
          dataIndex: 'outputGoodsId_dictText',
        },
        {
          title: this.$t('备注'),
          align: 'center',
          dataIndex: 'comment',
        },
        {
          title: this.$t('操作'),
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      queryParam: {
        gameInfo: '',
        state: '',
        consumeType: '2,3',
        column: 'createTime',
        order: 'desc',
      },
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total',{total:total})
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      url: {
        list: '/game/bisGame/list',
        delete: '/game/bisGame/delete',
      },
      typeId: '',
      sortList: [],
      stateList: [],
      treeItem: 0,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      defaultSelectedKeys: [],
    }
  },
  created() {
    this.getSortList()
    this.initDictConfig()
  },
  methods: {
    initDictConfig() {
      initDictOptions('bis_game.consume_type').then((res) => {
        if (res.success) {
          this.stateList = res.result
        }
      })
    },
    treeSelect(data) {
      this.treeItem = data[0]
      this.typeId = data[0];
      this.getList(1)
    },
    getSortList() {
      let that = this
      getAction('/game/bisGameType/rootList', { pageSize: 1000 }).then((res) => {
        if (res.success) {
          let list=res.result.records
          if (list.length > 0) {
            list.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.sortList = that.getDataByResult(list)
            that.sortList.unshift({ key: '', id: '', title: that.$t('全部') })
            that.treeItem = that.sortList[0].id
            that.typeId = that.sortList[0].id
            that.defaultSelectedKeys.push(that.sortList[0].key)
            that.getList(1)
          }
        }
      })
    },
    getHasChild(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      query.consumeType = 1
      getAction('/game/bisGameType/childList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.sortList = [...that.sortList]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    getList(num) {
      let that = this
      let querydata = {}
      querydata = that.queryParam
      that.ipagination.current = num
      querydata.pageNo = that.ipagination.current
      querydata.pageSize = that.ipagination.pageSize
      querydata.typeId = that.typeId
      that.loading = true
      getAction('/game/bisGame/list', querydata)
        .then((res) => {
          if (res.success) {
            res.result.records.forEach((col) => {
              if (col.state == 'Y') {
                col.states = true
              } else {
                col.states = false
              }
            })
            that.dataSource = res.result.records
            if (res.result.total) {
              that.ipagination.total = res.result.total
            } else {
              that.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          that.loading = false
        })
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record,3)
      this.$refs.modalForm.title = this.$t('编辑')
    },
    handleAdd() {
      this.$refs.modalForm.add(3)
      this.$refs.modalForm.title = this.$t('新增')
    },
    searchReset() {
      this.typeId = this.treeItem = this.sortList[0].id
      this.defaultSelectedKeys=[]
      this.defaultSelectedKeys.push(this.sortList[0].key)
      this.queryParam = {
        gameInfo: '',
        state: '',
        consumeType: '2,3',
        column: 'createTime',
        order: 'desc',
      }
      this.getList(1)
    },
    onChange(e) {
      e.state = e.states ? 'Y' : 'N'
      postAction('/game/bisGame/edit', { id: e.id, state: e.state }).then((res) => {
        if (res.success) {
          res.result.records.forEach((col) => {
            if (col.state == 'Y') {
              col.states = true
            } else {
              col.states = false
            }
          })
          this.dataSource = res.result.records
        }
      })
    },
    handleDelete(id) {
      let that = this
      if (!that.url.delete) {
        that.$message.error(that.$t('请设置url.delete属性'))
        return
      }
      deleteAction('/game/bisGame/delete', { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getList(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    modalFormOk() {
      this.getList(this.ipagination.current)
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination.current)
      console.log(pagination)
      this.getList(pagination.current)
    },
    reCalculatePage(count) {
      //总数量-count
      let total = this.ipagination.total - count
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize)
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex
      }
      console.log('currentIndex', currentIndex)
    },
  },
}
</script>
<style scoped>
.col-sort {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
}
.col-sort-selected {
  border-bottom: 1px solid #d9d9d9;
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
  background-color: #f0f7ff;
}
</style>